<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
*/
/*
	插件管理
	插件卸载：
		新框架插件——查找所有以插件标识开头的数据表——导出数据并备份——删除插件数据表——备份插件文件——删除插件文件，完成
		微赞兼容插件——获取需要删除和备份的数据表——导出数据并备份——删除插件数据表——备份插件文件——删除插件文件，完成
	插件更新：
		在云平台完成数据结构对比，生成更新sql下载执行；同时生成回滚sql保存在云平台（仅对字段修改生成回滚sql）
	插件回滚：
		文件本地直接回滚
		
	插件安装：
		文件下载
		
	场景体安装：
	检测到场景体安装时，整理所有需要安装的插件，把待安装插件存入会话，每安装成功一个插件，检测下是否还有需要安装的插件，如果有则继续安装下一个！
	
	
*/
defined('BY_JYA') or exit('error');
$_RQ['op']=$_RQ['op']?$_RQ['op']:'installed';
$manage_op=array('uninstall','hide','show','bak','info','update');
if(in_array($_RQ['op'],$manage_op)){
	$id=intval($_RQ['id']);
	if(!$id){
		exi('请先选择插件！','error');
	}
	$plugin=pdo_get('core_plugins',array('id'=>$id));
	if(!$plugin){
		exi('指定插件不存在！','error');
	}
}
$return=array();
$tabs=array(
	array('op'=>'installed','title'=>'应用列表'),
	array('op'=>'updates','title'=>'待更新应用'),
	array('op'=>'prepared','title'=>'待安装应用'),
	array('op'=>'local','title'=>'本地应用'),
	array('op'=>'api_list','title'=>'源自第三方安装'),
	array('op'=>'api_updates','title'=>'第三方待更新'),
	array('op'=>'api_prepared','title'=>'第三方待安装'),
);
$styles=get_plugin_styles();
if($_RQ['op'] == 'installed'){
	$allplugins = cache_read('cloud_getallplugins');
	if(!$allplugins){
			$allplugins=cloud_request('release.get_data.allplugins','','',true);
			cache_write('cloud_getallplugins',$allplugins);
	}
	$_AR['page']['title'] = '插件列表';
	$params=array();
	if($_RQ['type']){
		$params['type']=intval($_RQ['type']);
		$return['params']['type']=$_RQ['type'];
	}
	if(!empty($_RQ['title'])){
		$params['title like']='%'.trim($_RQ['title']).'%';
		$return['params']['title']=$_RQ['title'];
	}
	$orderby='star desc,paixu desc,id desc';
	$pindex = max(1, intval($_RQ['page']));
	$psize = 10;
	$total='';
	$fields=array('id','star','style','cloud_id','hide','release','image','version','name','title','price','endtime');
	$list=pdo_getslice('core_plugins',$params,array($pindex,$psize),$total,$fields,'',$orderby);
	foreach($list as &$item){
		$item['endtime']=$item['endtime']?date('Y-m-d H:m:s',$item['endtime']):'永久';
		$installed[$item['cloud_id']]=$item['cloud_id'];
	}
	$installed=array_keys($installed);
	$installed=implode(';',$installed);
	$params['installed']=$installed;
	$result=cloud_request('update.plugin.upendtime',$params);
	foreach($result as &$v){
		pdo_update('core_plugins',array('endtime'=>$v['endtime']),array('cloud_id'=>$v['pid']));
		foreach($list as $lv){
			if($lv['cloud_id']=$v['pid']){
				$lv['endtime']=$v['endtime'];
				$lv['endtime']=$lv['endtime']?date('Y-m-d H:m:s',$lv['endtime']):'永久';
			}
		}
	}
	$return['list']=$list;
	$totalpage=ceil($total/$psize);
	$totalpage=intval($totalpage);
	$return['totalpage'] =$totalpage;
	$return['params']['page'] =$pindex;
	$return['styles']=$styles;
	$return['htmls']=array(
		'type'=>'list',
		'tabs'=>$tabs,
		'list'=>array('tip'=>'已安装插件列表，星数，排序越大，越靠前！','data'=>'list','del_one'=>false,'delall'=>false,'edit'=>false,'list'=>array(
			array('name'=>'paixu','title'=>'排序','type'=>'string'),
			array('type'=>'img_string','title'=>'插件','img'=>'image',
			'data'=>array(
				array('title'=>'','name'=>'title'),
				array('title'=>'','name'=>'name')
				)
			),
			array('name'=>'star','title'=>'星数','type'=>'star','set'=>'star'),
			array('name'=>'style','title'=>'插件类型','type'=>'radio','options'=>'styles'),
			array('name'=>'price','title'=>'插件价格','type'=>'string'),
			array('name'=>'hide','title'=>'是否开启','type'=>'switch','open_value'=>0,'close_value'=>1,'set'=>'set'),
			array('name'=>'version','title'=>'插件版本','type'=>'string'),
			array('name'=>'endtime','title'=>'到期时间','type'=>'string'),
			array('op'=>'info','title'=>'查看详情','type'=>'post'),
		),'action'=>array(
			array('type'=>'href','op'=>'detail','title'=>'设置详情'),
			//array('type'=>'post','op'=>'hide','title'=>'隐藏','show'=>array('type >'=>1,'hide'=>0),'message'=>'隐藏后，该功能将无法使用，确定隐藏吗？'),
			//array('type'=>'post','op'=>'show','title'=>'显示','show'=>array('type >'=>1,'hide'=>1)),
			array('op'=>'install_data','title'=>'初始数据设置','type'=>'href'),
			array('op'=>'table','title'=>'数据表设置','type'=>'href'),
			array('type'=>'post','message'=>'确定已经设置好数据表和初始化数据吗？（默认以插件标识为数据表前缀的，无需设置！）','op'=>'config','title'=>'刷新配置文件'),
			array('type'=>'href','op'=>'down','title'=>'打包下载'),
			array('type'=>'href','op'=>'bak','title'=>'回滚'),
			array('type'=>'post','op'=>'uninstall','title'=>'卸载','message'=>'卸载将删除该插件的文件和数据，且不可恢复！确认卸载吗！'),
		)),
		'search_one'=>array('name'=>'title','add'=>false,'select_name'=>'style','is_radio'=>true,'options'=>'styles','select_title'=>'全部'),
	);
	exi($return);
}
if($_RQ['op']=='set'){
	$id=intval($_RQ['id']);
	if(!$id){
		exi('请先选择插件！','error');
	}
	$postdata=get_postdata();
	if(isset($postdata['hide'])){
		$update=array('hide'=>intval($postdata['hide']));
		pdo_update('core_plugins',$update,array('id'=>$id));
		$message=$update['hide']==1?'禁用成功！':'启用成功！';
	}
	if($message){
		exi($message);
	}else{
		exi('页面参数错误！','error');
	}
}
if ($_RQ['op'] == 'bak'){
	$return=array('item'=>array('id'=>$plugin['id']));
	$return['htmls']=array(
		'type'=>'edit',
		'post'=>'bak_post',
		'desc'=>'本回滚功能用于回滚系统更新时自动进行的备份。自行修改的文件无法在此处回滚！',
		'tabs'=>array(
			array('op'=>'installed','title'=>'返回插件列表'),
		),
		'edit'=>array(
			array('type'=>'time','name'=>'time','title'=>'回滚时刻','help'=>'设置回滚到哪一时刻'),
		),
	);
	exi($return);
}
if ($_RQ['op'] == 'bak_post'){
	//回滚插件
	$post=get_postdata();
	$plugin=pdo_get('core_plugins',array('id'=>intval($post['id'])));
	if(!$plugin){
		exi('指定插件不存在！','error');
	}
	$time=strtotime($post['time']);
	$baks=array();
	$mdir=ROOT_AT .'module_baks/'.$plugin['name'];
	//exi($mdir,'error');
	if(is_dir($mdir)){
		
		$bak = array();
		$bak_time=array();
		$baks=scandir($mdir);
		foreach($baks as $temp){
			if($temp=='.'||$temp=='..'){
				continue;
			} 
			$mtim=strrchr($temp,'.');
			$mtime=substr($mtim,1);
			if((int)$mtime > $time){
				$bak[$mtime]=$temp;
				$bak_time[]=$mtime;
			}
		}
		if($bak){
			arsort($bak_time,SORT_NUMERIC);
			if($plugin['type']==4){
				$plugin_dir=ROOT_D .'/addons/'.$plugin['name'];
			}else{
				$plugin_dir=ROOT_PLUGIN.$plugin['name'];
			}
			foreach($bak_time as $time){
				$zip = new ZipArchive();
				$zip->open($mdir.'/'.$bak[$time]);
				$zip->extractTo($plugin_dir);
				$zip->close();
				@unlink($mdir.'/'.$bak[$time]);
			}
			$bakr=strrchr($bak[$time],'.');
			$version=str_replace($bakr,'',$bak[$time]);
		}
	}
	$update=array('release'=>$time);
	if($version){
		$update['version']=$version;
	}
	pdo_update('core_plugins',$update,array('id'=>$plugin['id']));
	exi('成功将模块回滚至指定时刻！','success','installed');
}
if ($_RQ['op'] == 'detail'){
	//设置插件详细信息
	if($_RQ['postdata']){
		$post=get_postdata();
		$id=intval($post['id']);
		if(!$id){
			exi('请先选择插件！','error');
		}
		$update=array(
			'title'=>trim($post['title']),
			'version'=>trim($post['version']),
			'price'=>intval($post['price']),
			'days'=>intval($post['days']),
			'image'=>trim($post['image']),
			'hdps'=>ijson_encode($post['hdps']),
			'welcomehdps'=>ijson_encode($post['welcomehdps']),
			'description'=>trim($post['description']),
			'oneword'=>trim($post['oneword']),
			'tuijie'=>intval($post['tuijie']),
			'paixu'=>intval($post['paixu']),
			'salenum'=>intval($post['salenum']),
		);
		pdo_update('core_plugins',$update,array('id'=>$id));
		$update=array(
			'title'=>trim($post['title']),
			'price'=>intval($post['price']),
			'days'=>intval($post['days']),
			'image'=>trim($post['image']),
			'hdps'=>ijson_encode($post['hdps']),
			'desc'=>trim($post['description']),
			'tuijie'=>intval($post['tuijie']),
			'paixu'=>intval($post['paixu']),
			'salenum'=>intval($post['salenum']),
		);
		pdo_update('core_plugin_permissions',$update,array('plugin'=>$post['name'],'action'=>''));
		exi('设置成功！','','installed');
	}
	$id=intval($_RQ['id']);
	if(!$id){
		exi('请先选择要设置的插件！','error');
	}
	$item=pdo_get('core_plugins',array('id'=>$id),array('id','name','title','version','tuijie','image','description','oneword','hdps','welcomehdps'));
	$more=pdo_get('core_plugin_permissions',array('plugin'=>$item['name'],'action'=>''),array('price','days','paixu','desc','salenum','tuijie','hdps'));
	$item['hdps']=json_decode($item['hdps'],true);
	$welcomehdps =array(
		array('title'=>'他们都在用H5微商城','desc'=>'解决开店问题 助力小程序/H5/PC商城一体化','picurl'=>'../core/resource/images/welcomehdp01.jpg'),
		array('title'=>'粉丝变渠道商 激活圈内用户','desc'=>'分销加盟模式，让运营成为一种享受','picurl'=>'../core/resource/images/welcomehdp02.jpg'),
		array('title'=>'各种运营场景体 供你选择','desc'=>'根据自己的运营场景，个性组合搭建','picurl'=>'../core/resource/images/welcomehdp03.jpg'),
		array('title'=>'海量个性营销功能 助力市场激活','desc'=>'活跃，激活，促交面面俱到 让营销不在乏味','picurl'=>'../core/resource/images/welcomehdp04.jpg'),
	);
	$item['welcomehdps'] = !empty($item['welcomehdps']) ? json_decode($item['welcomehdps'],true) : $welcomehdps;
	$return['item']=array_merge($item,$more);
	$return['htmls']=array(
		'type'=>'edit',
		'desc'=>'设置应用详情',
		'edit'=>array(
			array('type'=>'string','name'=>'title','title'=>'插件名称'),
			array('type'=>'string','name'=>'oneword','title'=>'一句话描述'),
			array('type'=>'image','name'=>'image','title'=>'插件logo','help'=>'建议尺寸：311px*218px'),
			array('type'=>'images','name'=>'hdps','title'=>'幻灯片','help'=>'建议尺寸：640px*920px'),
			array('type'=>'array','title'=>'欢迎页幻灯片','name'=>'welcomehdps','add_tip'=>'添加一个欢迎幻灯片',
										'list'=>array(
											array('type'=>'string','name'=>'title','title'=>'标题'),
											array('type'=>'image','name'=>'picurl','title'=>'图片'),
											array('type'=>'string','name'=>'url','title'=>'地址'),
										),
										'details'=>array(
											array('type'=>'string','name'=>'title','title'=>'标题'),
											array('type'=>'string','name'=>'desc','title'=>'描述'),
											array('type'=>'image','name'=>'picurl','title'=>'图片','help'=>'推荐尺寸：750*900'),
											array('type'=>'link','name'=>'url','from'=>'action','title'=>'地址'),
										)
			),
			array('type'=>'switch','name'=>'tuijie','title'=>'是否推荐'),
			array('type'=>'string','name'=>'price','title'=>'插件价格'),
			array('type'=>'string','name'=>'days','title'=>'收费周期','help'=>'收费天数！'),
			array('type'=>'text','name'=>'description','title'=>'插件描述'),
			array('type'=>'string','name'=>'salenum','title'=>'安装数量'),
			array('type'=>'string','name'=>'paixu','title'=>'排序'),
		),
	);
	exi($return);
}
if ($_RQ['op'] == 'uninstall'){
	//卸载插件，从云平台获取执行代码执行之
	//删除插件数据表
	if(!$plugin['type'] || !$plugin['name']){
		exi('插件参数错误，无法卸载！','error');
	}
	$sql='';
	if($plugin['type']==4){
		//兼容插件
		$tables=pdo_getcolumn('core_old_plugins',array('name'=>$plugin['name']),'tables');
		$tables=str_array($tables);
		if($tables){
			foreach($tables as $table){
				$table=TABLE_PRE.$table;
				$sql.='drop table if exists `'.$table.'`;';
			}
		}
		pdo_delete('core_old_plugins',array('name'=>$plugin['name']));
	}else{
		$tables=pdo_fetchall("SHOW TABLES LIKE '".TABLE_PRE.$plugin['name']."_%'");
		foreach($tables as $table){
			$table=array_shift($table);
			$sql.='drop table if exists `'.$table.'`;';
		}
	}
	if($sql){
		pdo_query($sql);
	}
	//删除插件参数设置数据
	pdo_delete('core_account_plugin_setting',array('plugin'=>$plugin['name']));
	//删除插件权限数据
	pdo_delete('core_plugin_permissions',array('plugin'=>$plugin['name']));
	pdo_delete('core_plugin_subscribe',array('subscriber'=>$plugin['name']));
	pdo_delete('core_plugins',array('id'=>$plugin['id']));
	exi('卸载成功！');
}
if($_RQ['op'] == 'updates') { 
	//待更新组件列表，此处显示所有待更新的组件
	$params=array('is_my'=>0);
	if(!empty($_RQ['title'])){
		$params['title like']='%'.trim($_RQ['title']).'%';
		$return['params']['title']=$_RQ['title'];
	}
	$fields=array('id','cloud_id','title','version','release','image','basic');
	$list=pdo_getall('core_plugins',$params,$fields,'cloud_id');
	if($list){
		$cloud_ids=array_keys($list);
		$cloud_ids=implode(';',$cloud_ids);
		$post=array('cloud_ids'=>$cloud_ids);
		$versions=cloud_request('update.plugin.getup',$post);
		foreach($versions as $name=>$version){
			if($version['release']==$list[$name]['release']){
				//去掉无需更新的插件
				unset($list[$name]);
			}else{
				$list[$name]['new_version']=$version['version'];
				$list[$name]['sys_version']=$version['sys_version'];
				$list[$name]['v_desc']=$version['v_desc'];
				//$list[$name]['new_release']=$version['release'];
			}
		}
		$_SESSION['wait_updates']=$list;
	}
	$tabs[]=array('op'=>'update_all','title'=>'一键更新所有插件');
	$return['list']=$list;
	$return['styles']=$styles;
	$htmls=array(
		'type'=>'list',
		'tabs'=>$tabs,
		'list'=>array('tip'=>'更新存在新版本的功能插件','data'=>'list','del_one'=>false,'delall'=>false,'edit'=>false,'pagelist'=>false,'list'=>array(
			array('name'=>'image','title'=>'插件logo','type'=>'image'),
			array('name'=>'style','title'=>'插件类型','type'=>'radio','options'=>'styles'),
			array('name'=>'title','title'=>'插件名称','type'=>'string'),
			array('name'=>'version','title'=>'当前版本','type'=>'string'),
			array('name'=>'new_version','title'=>'最新版本','type'=>'string'),
			array('name'=>'v_desc','title'=>'最新更新说明','type'=>'string'),
			array('name'=>'sys_version','title'=>'最低系统版本支持','type'=>'string'),
			array('op'=>'info','title'=>'更新说明','type'=>'post'),
		),'action'=>array(
			array('type'=>'href','op'=>'update','title'=>'更新'),
		)),
		'search_one'=>array('name'=>'title','add'=>false),
	);
	$return['htmls']=$htmls;
	exi($return);
}
if($_RQ['op'] == 'api_updates') {
	//待更新组件列表，此处显示所有待更新的组件
	$params=array('api_domain <>'=>'','is_my'=>0);
	if(!empty($_RQ['title'])){
		$params['title like']='%'.trim($_RQ['title']).'%';
		$return['params']['title']=$_RQ['title'];
	}
	$fields=array('id','cloud_id','title','version','release','image','basic','api_domain');
	$list=pdo_getall('core_plugins',$params,$fields,'cloud_id');
	if($list){
		$cloud_ids=array_keys($list);
		$cloud_ids=implode(';',$cloud_ids);
		$post=array('cloud_ids'=>$cloud_ids);
		$api_shops=pdo_getall('core_api_shop',array(),array('id'));
		if($api_shops){
			foreach($api_shops as $item){
				$versions=api_request('api_shop.update.plugin.getup',$item['id'],$post);
				foreach($versions as $name=>$version){
					if($version['release']==$list[$name]['release']){
						//去掉无需更新的插件
						unset($list[$name]);
					}else{
						$list[$name]['new_version']=$version['version'];
						$list[$name]['sys_version']=$version['sys_version'];
						$list[$name]['v_desc']=$version['v_desc'];
						$list[$name]['updateurl']='core/cloud.module/update/id='.$list[$name]['id'].'&api_id='.$item['id'];
					}
				}
			}
		}
		$_SESSION['apiwait_updates']=$list;
	}
	$return['list']=$list;
	$return['styles']=$styles;
	$htmls=array(
		'type'=>'list',
		'tabs'=>$tabs,
		'list'=>array('tip'=>'更新存在新版本的功能插件','data'=>'list','del_one'=>false,'delall'=>false,'edit'=>false,'pagelist'=>false,'list'=>array(
			array('name'=>'image','title'=>'插件logo','type'=>'image'),
			array('name'=>'api_domain','title'=>'第三方域名','type'=>'string'),
			array('name'=>'style','title'=>'插件类型','type'=>'radio','options'=>'styles'),
			array('name'=>'title','title'=>'插件名称','type'=>'string'),
			array('name'=>'version','title'=>'当前版本','type'=>'string'),
			array('name'=>'new_version','title'=>'最新版本','type'=>'string'),
			array('name'=>'v_desc','title'=>'最新更新说明','type'=>'string'),
			array('name'=>'sys_version','title'=>'最低系统版本支持','type'=>'string'),
			array('op'=>'info','title'=>'更新说明','type'=>'post'),
		),'action'=>array(
			array('type'=>'href_item','action'=>'updateurl','title'=>'更新'),
		)),
		'search_one'=>array('name'=>'title','add'=>false),
	);
	$return['htmls']=$htmls;
	exi($return);
}
if($_RQ['op'] == 'info'){
	//前往应用商城查看更新说明，在新窗口打开更新说明页面。
	$url='http://s.jinyunweb.com/manage/index.php?action=store.plugins&op=detail&id='.$plugin['cloud_id'];
	exi('','','',$url);
}
if($_RQ['op'] == 'update_all') {
	//一键更新所有插件
	if(!$_SESSION['wait_updates']){
		exi('更新成功！','','installed');
	}
	$plugin=array_shift($_SESSION['wait_updates']);
	exi("准备更新【{$plugin['title']}】，请勿关闭页面！",'','//update/all=1&id='.$plugin['id']);
}
if($_RQ['op'] == 'update') {
	//更新插件
	$id=intval($_RQ['id']);
	$api_id=intval($_RQ['api_id']);
	$version=core_setting('version');
	if($api_id){
		$sys_version=$_SESSION['apiwait_updates'][$plugin['name']]['sys_version'];
	}else{
		$sys_version=$_SESSION['wait_updates'][$plugin['name']]['sys_version'];
	}
	if($sys_version && version_compare($version['version'], $sys_version) == -1) {
		exi('系统版本需要V-'.$sys_version.'以上，请先更新系统框架！','error');
	}
	$dir = ROOT_PLUGIN. $plugin['name'];
	if(!$_SESSION['download'] || !is_file(ROOT_AT.$plugin['name'].'.update')){
		$post=array('cloud_id'=>$plugin['cloud_id']);
		//查找插件现有数据结构
		if($plugin['type']==4){
			//第三方插件
			$tables=pdo_getcolumn('core_old_plugins',array('name'=>$plugin['name']),'tables');
			$tables=explode(';',trim($tables,';'));
		}else{
			$tables=pdo_fetchall("SHOW TABLES LIKE '".TABLE_PRE.$plugin['name']."_%'");
			if($tables){
				foreach($tables as &$row){
					$row=array_shift($row);
					$row=explode('_',$row,2);
					$row=$row['1'];
				}
			}
		}
		//读取插件数据结构
		$sqls=array();
		if($tables){
			foreach($tables as $table){
				if(!$table){
					continue;
				}
				$tablename=TABLE_PRE.$table;
				$sql=pdo_fetch('show create table '.$tablename);
				$sqls[$table]=$sql['Create Table'];
			}
		}
		$post['sqls']=$sqls;
		$post['release']=$plugin['release'];
		if($api_id){
			$dat=api_request('api_shop.update.plugin.build',$api_id,$post);
		}else{
			$dat=cloud_request('update.plugin.build',$post);
		}
		if(!$dat['plugin']){
			exi('更新失败，获取插件异常，请联系市场客服！','error');
		}
		//更新文件
		$upfiles=$files = array();
		if(!empty($dat['files'])) {
			$mdir=ROOT_AT .'module_baks/'.$plugin['name'];
			if(!is_dir($mdir)){
				cfc('files')->mkdirs($mdir);
			}
			$bak = $mdir.'/'.$plugin['version'].'.'.TIMESTAMP;
			$zip= new ZipArchive();
			$zip->open($bak, ZipArchive::CREATE);
			foreach($dat['files'] as $file) {
				$entry = $dir . $file['path'];
				if(!is_file($entry) || md5_file($entry) != $file['checksum']) {
					$files[] =$file['path'];
					$upfiles[]=$file;
				}
				if(is_file($entry) && md5_file($entry) != $file['checksum']) {
					$zip->addFile($entry,$file['path']);
				}
			}
			$zip->close();
		}
		//检查文件权限
		if(!empty($files)){
			$error=array();
			foreach($files as $f){
				$path = ROOT_PLUGIN.$plugin['name'].$f;
				if(file_exists($path)){
					if(!is_writable($path)){
					 $error[]=$path.'文件没有写入的权限';
					}
				}else{
					$path=get_dirname($path);
					if(!is_writable($path)){
					$error[]=$path.'文件夹没有写入的权限';
					}
				}
			}
			if($error){
				$error=implode(';',$error);
				exi($error,'error');
			}
		}
	
		if(!empty($files)){
			$post=array('cloud_id'=>$plugin['cloud_id'],'files'=>$files,'new'=>1);
			if($api_id){
				$files=api_request('api_shop.update.plugin.getmodule',$api_id,$post);
			}else{
				$files=cloud_request('update.plugin.getmodule',$post);
			}
			//下载更新文件时，如果内容较少，则一次性下载之，否则跳转下载页分批下载
			if($files['parts']==1){
				if($api_id){
					$data=api_request('api_shop.update.download',$api_id,array('id'=>$files['id'],'part'=>1),true);
				}else{
					$data=cloud_request('update.download',array('id'=>$files['id'],'part'=>1),true);
				}
				file_put_contents(ROOT_AT.$plugin['name'].'.update',$data);
			}else{
				$_SESSION['download']=array(
					'id'=>$files['id'],
					'parts'=>$files['parts'],
					'to'=>$plugin['name'].'.update',
					'back'=>'core/cloud.module/update/id='.$id,
				);
				$dat=serialize($dat);file_put_contents(ROOT_AT.$plugin['name'].'.update_data',$dat);
				exi('准备下载更新文件！','success','core/cloud.download/');
			}
		}
	}
	if(is_file(ROOT_AT.$plugin['name'].'.update')){
		$zip = new ZipArchive();
		$zip->open(ROOT_AT.$plugin['name'].'.update');
		$zip->extractTo($dir);
		$zip->close();
		@unlink(ROOT_AT.$plugin['name'].'.update');
		
	}
	if($_SESSION['download']){
		unset($_SESSION['download']);
	}
	if(!$dat){
		$dat=file_get_contents(ROOT_AT.$plugin['name'].'.update_data');
		if($dat){
			$dat=unserialize($dat);
		}
		@unlink(ROOT_AT.$plugin['name'].'.update_data');
	}
	//更新数据库结构
	if($dat['upsqls']){
		pdo_query($dat['upsqls']);
	}
	//执行额外操作
	if(!empty($dat['updata'])){
		foreach($dat['updata'] as $up){
			file_put_contents(ROOT_AT.'update.php',$up);
			require ROOT_AT.'update.php';
		}
	}
	@unlink(ROOT_AT.'update.php');
	//检测文件是否更新成功
	if($upfiles){
		foreach($upfiles as $file) {
			$entry = $dir . $file['path'];
			if(!is_file($entry) || md5_file($entry) != $file['checksum']) {
				exi("更新失败，请设置好模块根目录（".$dir."）的权限再更新！",'error');
			}
		}
	}
	//更新其他
	$data=array_fields(array('version','basic','style','intype','covers','menus','diypage','actionlinks','mobile_menus','release','istakeover','image','link','custom_access_type','is_legao','diy_legao','msgtpl','endtime'),$dat['plugin']);
	if($data['image'] && !$plugin['image']){
		$image=file_get_contents($data['image']);
		$data['image']=cfc('files')->source_save($image,'image','jpg','插件“'.$data['title'].'”logo');
	}else{
		unset($data['image']);
	}
	$menus=model('core/module')->get_filemenus($plugin['name']);
	if(count($menus)){
		$data['menus']=ijson_encode($menus);
	}
	pdo_update('core_plugins',$data,array('id'=>$id));
	model('core/msg_tpl')->check_tpl($plugin['name']);
	if($plugin['type']==4){
		$update=array_fields(array('setting','need_menu','tables'),$dat['plugin']);
		pdo_update('core_old_plugins',$update,array('name'=>$plugin['name']));
	}
	//检测权限数据是否已添加，如果没有，则添加之
	if(!pdo_getcolumn('core_plugin_permissions',array('plugin'=>$plugin['name']),'id')){
		$permission=array(
			'type'=>1,
			'plugin'=>$plugin['name'],
			'title'=>$plugin['title'],
			'image'=>$plugin['image'],
		);
		pdo_insert('core_plugin_permissions',$permission);
	}
	//检测更新权限数据
	if($dat['plugin']['permissions']){
		foreach($dat['plugin']['permissions'] as $perm){
			$check=pdo_getcolumn('core_plugin_permissions',array('plugin'=>$dat['plugin']['name'],'action'=>$perm['action'],'op'=>$perm['op']),'id');
			if($check){
				pdo_update('core_plugin_permissions',array('type'=>$perm['type'],'title'=>$perm['title']),array('id'=>$check));
			}else{
				$new_perm=array_fields(array('type','title','action','op'),$perm);
				$new_perm['plugin']=$dat['plugin']['name'];
				pdo_insert('core_plugin_permissions',$new_perm);
			}
		}
	}
	//检测更新插件事件订阅
	if($dat['plugin']['subscribe']){
		foreach($dat['plugin']['subscribe'] as $subscribe){
			$data=array(
				'subscriber'=>$subscribe['subscriber'],
				'plugin'=>$subscribe['plugin'],
				'event'=>$subscribe['event'],
			);
			$check=pdo_getcolumn('core_plugin_subscribe',$data,'id');
			if(!$check){
				pdo_insert('core_plugin_subscribe',$data);
			}
		}
	}
	//插件初始化数据
	if($dat['plugin']['install_data']){
		foreach($dat['plugin']['install_data'] as $table=>$data){
			$check=pdo_count('core_plugin_install_data',array('plugin_name'=>$dat['plugin']['name'],'table'=>$table));
			if(!$check){
				pdo_insert('core_plugin_install_data',array('plugin_name'=>$dat['plugin']['name'],'table'=>$table));
			}
			$check=pdo_count($table);
			if($check){
				continue;
			}
			foreach($data as $row){
				pdo_insert($table,$row);
			}
		}
	}
	if(intval($_RQ['all']) && $_SESSION['wait_updates'] && !$api_id){
		exi('','','update_all');
	}
	exi('更新成功！','','installed');
}
if($_RQ['op'] == 'prepared'){
	$_AR['page']['title'] = '待安装插件列表';
	$installed = pdo_getall('core_plugins',array(),array('cloud_id'),'cloud_id');
	$installed=array_keys($installed);
	$installed=implode(';',$installed);
	$params['installed']=$installed;
	if(!empty($_RQ['title'])){
		$params['title']=trim($_RQ['title']);
	}
	$result=cloud_request('update.plugin.getbuyed',$params);
	//$_SESSION['wait_installs']=$result;
	$return['list']=$result;
	$return['styles']=$styles;
	$htmls=array(
		'type'=>'list',
		'tabs'=>$tabs,
		'list'=>array('tip'=>'已购买但尚未安装的插件。安装大插件时，可能需要等长一点时间，请耐心等待，不要重复点击。如果这里没有您想要安装的插件，请先前往应用商城购买！','data'=>'list','del_one'=>false,'delall'=>false,'edit'=>false,'pagelist'=>false,'list'=>array(
			array('name'=>'image','title'=>'插件logo','type'=>'image'),
			array('name'=>'style','title'=>'插件类型','type'=>'radio','options'=>'styles'),
			array('name'=>'title','title'=>'插件名称','type'=>'string'),
			array('name'=>'version','title'=>'插件版本','type'=>'string'),
		),'action'=>array(
			array('type'=>'href','op'=>'install','title'=>'安装'),
		)),
		'search_one'=>array('name'=>'title','add'=>false),
	);
	$return['htmls']=$htmls;
	exi($return);
}
if($_RQ['op'] == 'api_prepared'){
	$_AR['page']['title'] = '待安装插件列表';
	$installed = pdo_getall('core_plugins',array(),array('cloud_id'),'cloud_id');
	$installed=array_keys($installed);
	$installed=implode(';',$installed);
	$params['installed']=$installed;
	if(!empty($_RQ['title'])){
		$params['title']=trim($_RQ['title']);
	}
	$api_shops=pdo_getall('core_api_shop',array(),array('id'));
	$list=array();
	if($api_shops){
		foreach($api_shops as $item){
			$result=api_request('api_shop.update.plugin.getbuyed',$item['id'],array('installed'=>$installed));
			foreach($result as &$rv){
				$rv['domain']=$item['domain'];
				$rv['installurl']='core/cloud.module/install/id='.$rv['id'].'&api_id='.$item['id'];
				$list[]=$rv;
			}
		}
	}
	$return['list']=$list;
	$return['styles']=$styles;
	$htmls=array(
		'type'=>'list',
		'tabs'=>$tabs,
		'list'=>array('tip'=>'已购买但尚未安装的插件。安装大插件时，可能需要等长一点时间，请耐心等待，不要重复点击。如果这里没有您想要安装的插件，请先前往应用商城购买！','data'=>'list','del_one'=>false,'delall'=>false,'edit'=>false,'pagelist'=>false,'list'=>array(
			array('name'=>'image','title'=>'插件logo','type'=>'image'),
			array('name'=>'style','title'=>'插件类型','type'=>'radio','options'=>'styles'),
			array('name'=>'title','title'=>'插件名称','type'=>'string'),
			array('name'=>'version','title'=>'插件版本','type'=>'string'),
		),'action'=>array(
			array('type'=>'post_item','action'=>'installurl','title'=>'安装'),
		)),
		'search_one'=>array('name'=>'title','add'=>false),
	);
	$return['htmls']=$htmls;
	exi($return);
}
if($_RQ['op'] == 'install_all') {
	if(!$_SESSION['wait_installs'] || count($_SESSION['wait_installs'])==0){
		exi('一键安装成功！','','installed');
	}
	$plugin=array_shift($_SESSION['wait_installs']);
	if($plugin['title'] && $plugin['id']){
		$url='//install/id='.$plugin['id'];
		if($plugin['assembly']){
			$url.='&assembly=1';
		}
		exi("准备安装【{$plugin['title']}】，请勿关闭页面！",'',$url);
	}else{
		exi('','','install_all');
	}
}
if($_RQ['op'] == 'install') {
	//安装插件	
	$id=intval($_RQ['id']);
	$api_id=intval($_RQ['api_id']);
	if(!$id){
		exi('请先选择要安装的插件！','error');
	}
	if(!$_RQ['assembly']){
		//正常安装插件，检查是否有组件待安装
		if($api_id){
			$diy_legao=api_request('api_shop.update.plugin.pre_install',$api_id,array('cloud_id'=>$id));
		}else{
			$diy_legao=cloud_request('update.plugin.pre_install',array('cloud_id'=>$id));
		}
		if($diy_legao){
			foreach($diy_legao as $legao){
				//将组件塞进待安装列表
				$has=false;
				foreach($_SESSION['wait_installs'] as $wait){
					if($wait['id']==$legao['id']){
						$has=true;
						break;
					}
				}
				if(!$has){
					$legao['assembly']=1;
					array_unshift($_SESSION['wait_installs'][],$legao);
				}
			}
		}
	}
	
	set_time_limit(0);
	if(!$_SESSION['download'] || !is_file(ROOT_AT.$id.'.install') || !is_file(ROOT_AT.$id.'.config')){
		if (pdo_getcolumn('core_plugins',array('cloud_id'=>$id),'id')) {
			exi('插件已经安装或是唯一标识已存在！','error');
		}
		
		if(is_file(ROOT_AT.$id.'.install')){
			@unlink(ROOT_AT.$id.'.install');
		}
		//获取插件基本数据
		$post=array('cloud_id'=>$id,'new'=>1);
		if($api_id){
			$module=api_request('api_shop.update.plugin.install',$api_id,$post);
		}else{
			$module=cloud_request('update.plugin.install',$post);
		}
		//安装环境检测
		/*if($module['bases']){
			$need_plugin=array();
			$base_plugins=trim($module['bases'],';');
			$base_plugins=explode(';',$base_plugins);
			foreach($base_plugins as $cloud_id){
				$check=pdo_getcolumn('core_plugins',array('cloud_id'=>$cloud_id),'id');
				if(!$check){
					$need_plugin[]=$cloud_id;
				}
			}
			if(!empty($need_plugin)){
				//cache_delete($id);
				exi('安装失败，该插件需要依赖一些插件才能正常使用！请先安装以下插件：'.implode(',',$need_plugin).'（以上为插件ID，请前往应用市场搜索该插件ID，并购买安装）','error');
			}
		}*/	
		//获取插件安装文件
		if(!is_dir(ROOT_PLUGIN.$module['name'])){
			//本地没有文件，直接下载
			if($api_id){
				$download=api_request('api_shop.update.plugin.installdata',$api_id,array('cloud_id'=>$id));
			}else{
				$download=cloud_request('update.plugin.installdata',array('cloud_id'=>$id));
			}
		}else{
			//对比更新
			if($api_id){
				$res=api_request('api_shop.update.plugin.build',$api_id,array('cloud_id'=>$id,'only_file'=>true));
			}else{
				$res=cloud_request('update.plugin.build',array('cloud_id'=>$id,'only_file'=>true));
			}
			$upfiles=array();
			foreach($res['files'] as $row){
				$file=ROOT_PLUGIN.$module['name'].$row['path'];
				if(!is_file($file) || md5_file($file)!=$row['checksum']){
					$upfiles[]=$row['path'];
				}
			}
			if(!empty($upfiles)){
				//获取差异文件
				$post=array('cloud_id'=>$id,'files'=>$upfiles,'new'=>1);
				if($api_id){
					$download=api_request('api_shop.update.plugin.getmodule',$api_id,$post);
				}else{
					$download=cloud_request('update.plugin.getmodule',$post);
				}
			}else{
				//无需下载文件
				$download=array();
			}
		}
		if($download['parts']==1){
			if($api_id){
				$install_data=api_request('api_shop.update.download',$api_id,array('id'=>$download['id'],'part'=>1),true);
			}else{
				$install_data=cloud_request('update.download',array('id'=>$download['id'],'part'=>1),true);
			}
			file_put_contents(ROOT_AT.$id.'.install',$install_data);
		}elseif($download['parts'] > 1){
			//将插件数据保存到临时文件中，开始下载文件
			$config=serialize($module);
			file_put_contents(ROOT_AT.$id.'.config',$config);
			$_SESSION['download']=array(
				'id'=>$download['id'],
				'parts'=>$download['parts'],
				'to'=>$id.'.install',
				'back'=>'core/cloud.module/install/id='.$id,
			);
			exi('准备下载安装文件！','','core/cloud.download/');
		}
		//parts==0表示无需额外下载数据
	}
	if(!$module){
		$module=file_get_contents(ROOT_AT.$id.'.config');
		$module=unserialize($module);
		@unlink(ROOT_AT.$id.'.config');
	}
	if(is_file(ROOT_AT.$id.'.install')){
		
		$zip = new ZipArchive();
		$zip->open(ROOT_AT.$id.'.install');
		$zip->extractTo(ROOT_PLUGIN.$module['name']);
		$zip->close();
		@unlink(ROOT_AT.$id.'.install');
	}
	if($_SESSION['download']){
		unset($_SESSION['download']);
	}
	//安装数据表
	if(!empty($module['install'])){
		pdo_query($module['install']);
	}
	//插入初始化数据
	if($module['install_data']){
		foreach($module['install_data'] as $table=>$data){
			$check=pdo_count($table);
			if($check){
				continue;
			}
			foreach($data as $row){
				pdo_insert($table,$row);
			}
		}
	}
	$data=array_fields(array('name','basic','title','type','style','intype','version','description','covers','menus','diypage','mobile_menus','release','istakeover','link','custom_access_type','is_legao','diy_legao','msgtpl','endtime'),$module);
	if(!$data['name']){
		exi('插件参数错误，安装失败！','error');
	}
	if($module['image']){
		$image=file_get_contents($module['image']);
		$data['image']=cfc('files')->source_save($image,'image','jpg','插件“'.$module['title'].'”logo');
	}
	if($module['hdp']){
		$hdps=json_decode($module['hdp'],true);
		foreach($hdps as &$hv){
			$image=file_get_contents($hv);
			$hv=cfc('files')->source_save($image,'image','jpg','插件“'.$data['title'].'”hdps');
		}
		$data['hdps']=ijson_encode($hdps);
	}
	if($module['welcomehdps']){
		$welcomehdps=json_decode($module['welcomehdps'],true);
		foreach($welcomehdps as &$whv){
			$image=file_get_contents($whv['picurl']);
			$whv['picurl']=cfc('files')->source_save($image,'image','jpg','插件“'.$data['title'].'”welcomehdps');
		}
		$data['welcomehdps']=ijson_encode($welcomehdps);
	}
	$data['cloud_id']=$id;
	//第三方域名：
	if($api_id){
		$data['api_domain']=pdo_getcolumn('core_api_shop',array('id'=>$api_id),'domain');
	}
	$menus=model('core/module')->get_filemenus($data['name']);
	if(count($menus)){
		$data['menus']=ijson_encode($menus);
	}
	pdo_insert('core_plugins',$data);
	model('core/msg_tpl')->check_tpl($data['name']);
	if($data['type']==4){
		$id=pdo_insertid();
		$old_insert=array_fields(array('name','need_menu','setting','tables'),$module);
		pdo_insert('core_old_plugins',$old_insert);
	}
	
	if($module['permissions']){
		foreach($module['permissions'] as $perm){
			$new_perm=array_fields(array('type','title','action','op'),$perm);
			$new_perm['plugin']=$data['name'];
			pdo_insert('core_plugin_permissions',$new_perm);
		}
	}else{
		//插入基础权限集
		$permission=array(
			'type'=>1,
			'plugin'=>$data['name'],
			'title'=>$data['title'],
			'image'=>$data['image'],
		);
		pdo_insert('core_plugin_permissions',$permission);
	}
	if($module['subscribe']){
		foreach($module['subscribe'] as $subscribe){
			$data=array(
				'subscriber'=>$subscribe['subscriber'],
				'plugin'=>$subscribe['plugin'],
				'event'=>$subscribe['event'],
			);
			$check=pdo_getcolumn('core_plugin_subscribe',$data,'id');
			if(!$check){
				pdo_insert('core_plugin_subscribe',$data);
			}
		}
	}
	if($_SESSION['wait_installs']){
		//取消一键安装！
		//exi('','','install_all');
	}
	exi('安装成功！如果模块尚未出现在扩展功能栏，请刷新页面！','','installed');
}
if($_RQ['op'] == 'local'){
	//本地应用安装和更新，含有config.json配置文件的应用即认为是本地应用
	$local_plugins=model('core/module')->local_plugins();	
	$return['list']=$local_plugins;
	$return['htmls']=array(
		'type'=>'list',
		'tabs'=>$tabs,
		'list'=>array('data'=>'list','key'=>'name','tip'=>'本地插件列表','del_one'=>false,'delall'=>false,'edit'=>false,'list'=>array(
			array('name'=>'logo','title'=>'插件logo','type'=>'image'),
			array('name'=>'title','title'=>'插件名称','type'=>'string'),
			array('name'=>'name','title'=>'插件标识','type'=>'string'),
			array('name'=>'old_version','title'=>'当前版本','type'=>'string'),
			array('name'=>'version','title'=>'待更新版本','type'=>'string'),
		),'action'=>array(
			array('type'=>'post','op'=>'local_install','title'=>'安装','show'=>array('install_status'=>0)),
			array('type'=>'post','op'=>'local_update','title'=>'更新','show'=>array('has_new_version'=>1)),
			array('op'=>'install_data','title'=>'初始数据设置','type'=>'href','show'=>array('install_status'=>1)),
			array('op'=>'table','title'=>'数据表设置','type'=>'href','show'=>array('install_status'=>1)),
			array('type'=>'post','message'=>'确定已经设置好数据表和初始化数据吗？（默认以插件标识为数据表前缀的，无需设置！）','op'=>'config','title'=>'刷新配置文件','show'=>array('install_status'=>1)),
			array('type'=>'href','op'=>'down','title'=>'打包下载','show'=>array('install_status'=>1)),
			array('type'=>'post','op'=>'local_uninstall','title'=>'卸载','show'=>array('install_status'=>1),'message'=>'确认卸载吗！'),
		)),
	);
	exi($return);
}
if($_RQ['op'] == 'api_list'){
	$_AR['page']['title'] = '插件列表';
	$params=array('api_domain <>'=>'');
	if($_RQ['type']){
		$params['type']=intval($_RQ['type']);
		$return['params']['type']=$_RQ['type'];
	}
	if(!empty($_RQ['title'])){
		$params['title like']='%'.trim($_RQ['title']).'%';
		$return['params']['title']=$_RQ['title'];
	}
	$orderby='star desc,paixu desc,id desc';
	$pindex = max(1, intval($_RQ['page']));
	$psize = 10;
	$total='';
	$fields=array('id','star','style','cloud_id','hide','release','image','version','name','title','price','endtime','api_domain');
	$list=pdo_getslice('core_plugins',$params,array($pindex,$psize),$total,$fields,'',$orderby);
	foreach($list as &$item){
		$item['endtime']=$item['endtime']?date('Y-m-d H:m:s',$item['endtime']):'永久';
	}
	$return['list']=$list;
	$totalpage=ceil($total/$psize);
	$totalpage=intval($totalpage);
	$return['totalpage'] =$totalpage;
	$return['params']['page'] =$pindex;
	$return['styles']=$styles;
	$return['htmls']=array(
		'type'=>'list',
		'tabs'=>$tabs,
		'list'=>array('tip'=>'[<red>温馨提示</red>]</br>1、所谓第三方安装，即通过第三方的应用市场，安装的应用！</br>2、移步系统管理--云服务--第三方市场，创建一个第三方市场，然后在第三方市场列表页，点击前往应用市场。3、所有第三方应用，所有权归第三方解释，一切购买安装动作，都是在第三方独立操作！</br>3、如果已安装的应用，再第三方购买后，只能更新，且版本必须大于已安装的应用版本！','data'=>'list','del_one'=>false,'delall'=>false,'edit'=>false,'list'=>array(
			array('name'=>'paixu','title'=>'排序','type'=>'string'),
			array('type'=>'img_string','title'=>'插件','img'=>'image',
			'data'=>array(
				array('title'=>'','name'=>'title'),
				array('title'=>'','name'=>'name')
				)
			),
			array('name'=>'api_domain','title'=>'来源第三方域名','type'=>'string'),
			array('name'=>'star','title'=>'星数','type'=>'star','set'=>'star'),
			array('name'=>'style','title'=>'插件类型','type'=>'radio','options'=>'styles'),
			array('name'=>'price','title'=>'插件价格','type'=>'string'),
			array('name'=>'hide','title'=>'是否开启','type'=>'switch','open_value'=>0,'close_value'=>1,'set'=>'set'),
			array('name'=>'version','title'=>'插件版本','type'=>'string'),
			array('name'=>'endtime','title'=>'到期时间','type'=>'string'),
			array('op'=>'info','title'=>'查看详情','type'=>'post'),
		),'action'=>array(
			array('type'=>'href','op'=>'detail','title'=>'设置详情'),
			//array('type'=>'post','op'=>'hide','title'=>'隐藏','show'=>array('type >'=>1,'hide'=>0),'message'=>'隐藏后，该功能将无法使用，确定隐藏吗？'),
			//array('type'=>'post','op'=>'show','title'=>'显示','show'=>array('type >'=>1,'hide'=>1)),
			array('op'=>'install_data','title'=>'初始数据设置','type'=>'href'),
			array('op'=>'table','title'=>'数据表设置','type'=>'href'),
			array('type'=>'post','message'=>'确定已经设置好数据表和初始化数据吗？（默认以插件标识为数据表前缀的，无需设置！）','op'=>'config','title'=>'刷新配置文件'),
			array('type'=>'href','op'=>'down','title'=>'打包下载'),
			array('type'=>'href','op'=>'bak','title'=>'回滚'),
			array('type'=>'post','op'=>'uninstall','title'=>'卸载','message'=>'卸载将删除该插件的文件和数据，且不可恢复！确认卸载吗！'),
		)),
		'search_one'=>array('name'=>'title','add'=>false,'select_name'=>'style','is_radio'=>true,'options'=>'styles','select_title'=>'全部'),
	);
	exi($return);
}
$local_ops=array('local_install','local_update','local_uninstall');
if(in_array($_RQ['op'],$local_ops)){
	$plugin_name=trim($_RQ['name']);
	if(!$plugin_name){
		exi('请先选择要安装的插件！','error');
	}
	if(preg_match('/\W/',$plugin_name)){
		exi('插件标识不合法！','error');
	}
	$config_data = model('core/module')->get_manifest($plugin_name);
	if(empty($config_data)){
		exi('插件配置文件不存在！','error');
	}
	if($config_data['application']['identifie']!=$plugin_name){
		exi($config_data['application']['identifie'].'插件配置文件-插件标识跟插件目录文件名不一致！'.$plugin_name,'error');
	}
}
if($_RQ['op'] == 'local_install'){
	//本地安装
	$check=pdo_get('core_plugins',array('name'=>$plugin_name),'id');
	if($check){
		exi('插件已安装，请勿重复安装！','error');
	}
	$check_config_data = model('core/module')->manifestxml_check($plugin_name, $config_data);
	if (is_error($check_config_data)) {
		exi($check_config_data['message'],'error');
	}
	$updatedata = model('core/module')->int_update($config_data);
	if (file_exists(ROOT_PLUGIN . $updatedata['name'] . '/icon-custom.jpg')) {
			$updatedata['image'] = '../addons/' . $updatedata['name'] . '/icon-custom.jpg';
	} else {
			$updatedata['image'] = '../addons/' . $updatedata['name'] . '/icon.jpg';
	}
	//安装数据库
	model('core/module')->run_xmlsql($config_data, 'install');
	$menus=model('core/module')->get_filemenus($updatedata['name']);
	$updatedata['menus']=$menus?ijson_encode($menus):$updatedata['menus'];
	$config_data['need_menu']=$updatedata['need_menu'];
	unset($updatedata['need_menu']);
	pdo_insert('core_plugins',$updatedata);
	model('core/module')->insert_more($updatedata,$config_data);
	exi('安装成功！如果模块尚未出现在扩展功能栏，请刷新页面！','','local');
}
if($_RQ['op'] == 'local_update'){
	//本地更新	
	$plugin=pdo_get('core_plugins',array('name'=>$plugin_name),array('id','version','release'));
	if(!$plugin){
		exi('插件尚未安装，无法更新！','error');
	}
	if($config_data && version_compare($plugin['version'],$config_data['application']['version'],'>')){
		exi('插件已是最新，无需更新！','error');
	}
	$updatedata = model('core/module')->int_update($config_data);
	//安装数据库
	model('core/module')->run_xmlsql($config_data, 'update');
	$menus=model('core/module')->get_filemenus($plugin_name);
	if(count($menus)){
		$updatedata['menus']=ijson_encode($menus);
	}
	pdo_update('core_plugins',$updatedata,array('id'=>$plugin['id']));
	model('core/module')->update_more($updatedata,$config_data);
	exi('更新成功！','','local');
}
if($_RQ['op'] == 'local_uninstall'){
	//本地卸载：删除插件表记录、删除权限表记录、删除插件数据表
	$plugin=pdo_get('core_plugins',array('name'=>$plugin_name),array('id','name','title'));
	if(!$plugin){
		exi('插件尚未安装，无法卸载！','error');
	}
	model('core/module')->unrun_xmlsql($config_data,$plugin_name);
	pdo_delete('core_plugins',array('id'=>$plugin['id']));
	pdo_delete('core_plugin_permissions',array('plugin'=>$plugin['name']));
	pdo_delete('core_old_plugins',array('name'=>$plugin['name']));
	exi("插件【{$plugin['title']}】卸载成功",'','local');
}
if($_RQ['op'] == 'config'){
	//生成配置文件
	$id=intval($_RQ['id']);
	if($id){
		$plugin_name=pdo_getcolumn('core_plugins',array('id'=>$id),'name');
	}else{
		$plugin_name=$_RQ['name'];
	}
	if(!$plugin_name){
		exi('请先选择插件！','error');
	}
	$manifestxml=model('core/module')->int_manifest($plugin_name);
	file_put_contents(ROOT_PLUGIN.$plugin_name.'/manifest.xml',$manifestxml);
	exi('生成配置成功');
}
if($_RQ['op']=='down'){
	$id=intval($_RQ['id']);
	if($id){
		$plugin=pdo_get('core_plugins',array('id'=>$id),array('name','image'));
		$name=$plugin['name'];
	}else{
		$name=$_RQ['name'];
	}
	if(!$name || preg_match('/\W/',$name)){
		exi('下载出错！','error');
	}
	$dir=ROOT_PLUGIN.$name;
	if(!is_dir($dir)){
		exi('插件不存在！','error');
	}
	if(!is_file($dir.'/manifest.xml')){
		exi('请先生成配置文件！','error');
	}
	$icon=ROOT_PLUGIN.$name.'/icon.jpg';
	if(!file_exists($icon) && file_exists(ROOT_AT.$plugin['image'])){
		copy(ROOT_AT.$plugin['image'],$icon);
	}
	$url=download_url('core/cloud.module/down_load/name='.$name);
	exi('','',$url);
}
if($_RQ['op']=='down_load'){
	//下载包
	$name=$_RQ['name'];
	if(!$name){
		exi('下载插件包出错！','error');
	}
	$dir=ROOT_PLUGIN.$name;
	do{
		$zip=ROOT_AT.random(10).'.temp';
	}while(is_file($zip));
	cfc('files')->zip($dir,$zip);
	header('content-type: application/zip');
	header('content-disposition: attachment; filename="' . $name . '.zip"');
	readfile($zip);
	@unlink($zip);
	exit();
}
if($_RQ['op']=='table'){
	//插件数据表管理，对于兼容插件，开发者在此处设置插件所属数据表，方便同步云平台
	$id=intval($_RQ['id']);
	if($id){
		$plugin_name=pdo_getcolumn('core_plugins',array('id'=>$id),'name');
	}else{
		$plugin_name=$_RQ['name'];
	}
	if($plugin_name){
		$_SESSION['module']['plugin_name']=$plugin_name;
	}
	$pindex = max(1, intval($_RQ['page']));
	$psize = 15;
	$params=array('plugin_name'=>$_SESSION['module']['plugin_name']);
	//忽略项目名称
	if(!empty($_RQ['name'])){
		$params['name like']='%'.trim($_RQ['name']).'%';
		$return['params']['name']=$_RQ['name'];
	}
	$list=pdo_getslice('core_plugin_tables',$params,array($pindex,$psize),$total,array(),'','id desc');
	$return['list']=$list?$list:array();
	$totalpage=ceil($total/$psize);
	$totalpage=intval($totalpage);
	$return['totalpage'] =$totalpage;
	$return['params']['page'] =$pindex;
	$return['htmls']=array(
		'type'=>'list',
		'tabs'=>array(
			array('op'=>'installed','title'=>'回到插件列表'),
			array('op'=>'table_add','title'=>'添加数据表'),
		),
		'list'=>array('data'=>'list','tip'=>'这里是用于支持打包插件，所需的设置；大部分原生插件是不需要设置数据表的，除部分兼容插件（安装的数据表名跟插件标识不一致的才需要）。','edit_op'=>'table_edit','del_op'=>'table_del','list'=>array(
			array('type'=>'string','name'=>'name','title'=>'数据表名'),
		)),
		'search_one'=>array('name'=>'name','add_op'=>'table_add'),
	);
	exi($return);
}
if($_RQ['op']=='install_data'){
	//设置初始化数据设置
	$id=intval($_RQ['id']);
	if($id){
		$name=pdo_getcolumn('core_plugins',array('id'=>$id),'name');
	}else{
		$name=$_RQ['name'];
	}
	if($name){
		$_SESSION['module']['plugin_name']=$name;
	}
	$name=$_SESSION['module']['plugin_name'];
	$list=pdo_getall('core_plugin_install_data',array('plugin_name'=>$name));
	if($list){
		foreach($list as &$item){
			if(!$item['type']){
				$item['num']='表内所有数据';
			}
		}
	}
	$return['list']=$list;
	$return['htmls']=array(
		'type'=>'list',
		'tabs'=>array(
			array('op'=>'installed','title'=>'回到插件列表'),
			array('op'=>'data_edit','title'=>'添加初始化数据'),
		),
		'list'=>array('data'=>'list','tip'=>'这里是用于支持打包插件，所需的设置；（大部分插件是不需要初始化数据的，部分插件可能需要初始化数据。例如：默认任务执行数据，默认模板消息数据等），选择需要初始化数据的表，打包时会追加到安装数据里面','edit_op'=>'data_edit','del_op'=>'data_del','pagelist'=>false,'list'=>array(
			array('type'=>'string','name'=>'table','title'=>'数据表名'),
			array('type'=>'string','name'=>'num','title'=>'初始化数据条数'),
		)),
		'search_one'=>array('name'=>'table','add_op'=>'data_edit'),
	);
	exi($return);
}
if($_RQ['op']=='data_edit'){
	if($_RQ['postdata']){
		$post=get_postdata();
		if(!pdo_tableexists($post['table'])){
				exi($post['table'].'表不存在！','error');
		}
		$data=array_fields(array('table','type','num'),$post);
		$id=intval($post['id']);
		if($id){
			pdo_update('core_plugin_install_data',$data,array('id'=>$id));
		}else{
			$data['plugin_name']=$_SESSION['module']['plugin_name'];
			pdo_insert('core_plugin_install_data',$data);
		}
		exi('操作成功！','','install_data');
	}
	$id=intval($_RQ['id']);
	if($id){
		$item=pdo_get('core_plugin_install_data',array('id'=>$id));
	}else{
		$item=array();
	}
	$return['types']=array(
		'0'=>'表内全部数据',
		'1'=>'自定义条数',
	);
	$return['item']=$item;
	$return['htmls']=array(
		'type'=>'edit',
		'desc'=>'设置初始化数据',
		'tabs'=>array(
			array('op'=>'install_data','title'=>'返回初始化数据列表'),
		),
		'edit'=>array(
			array('type'=>'string','name'=>'table','title'=>'填写数据表名','help'=>'填写不含表前缀的数据表名'),
			array('type'=>'radio','name'=>'type','title'=>'数据条数类型','options'=>'types'),
			array('type'=>'string','name'=>'num','show'=>array('type',1),'title'=>'数据条数','help'=>'设置该数据表前多少条数据作为初始化数据'),
		),
	);
	exi($return);
}
if($_RQ['op']=='data_del'){
	$id=intval($_RQ['id']);
	if($id){
		pdo_delete('core_plugin_install_data',array('id'=>$id));
	}
	$del=trim($_RQ['del'],';');
	if($del){
		$del=explode(';',$del);
		foreach($del as $id){
			$id=intval($id);
			if($id){
				pdo_delete('core_plugin_install_data',array('id'=>$id));
			}
		}
	}
	exi('删除成功！');
}
if($_RQ['op']=='table_add'){
	//插件数据表管理，对于兼容插件，开发者在此处设置插件所属数据表，方便同步云平台
	if(!empty($_RQ['title'])){
		$tables=pdo_fetchall("SHOW TABLES LIKE '%".$_RQ['title']."%'");
		$return['params']['title']=$_RQ['title'];
	}else{
		$tables=pdo_fetchall("SHOW TABLES");
	}
	$has=pdo_getall('core_plugin_tables',array('plugin_name'=>$_SESSION['module']['plugin_name']),array('name'),'name');
	$list=array();
	$num=0;//每次最多读取50张表
	foreach($tables as &$table){
		$table=array_shift($table);
		$table=explode('_',$table,2);
		$table=$table['1'];
		if(!$has[$table] && $num<50){
			$list[]=array('id'=>$table);
			$num++;
		}
	}
	$return['list']=$list;
	$return['htmls']=array(
		'type'=>'list',
		'tabs'=>array(
			array('op'=>'installed','title'=>'回到插件列表'),
			array('op'=>'table','title'=>'查看已添加的数据表'),
		),
		'list'=>array('data'=>'list','edit'=>false,'pagelist'=>false,'del_one'=>false,'delall'=>false,'del_message'=>'确认添加吗？','del_title'=>'添加','list'=>array(
			array('type'=>'string','name'=>'id','title'=>'数据表名'),
		),'batch'=>array(
			array('type'=>'post','url'=>'table_add_post','title'=>'一键添加'),
		)),
		'search_one'=>array('name'=>'title','add'=>false),
	);
	exi($return);
}
if($_RQ['op']=='table_add_post'){
	$ids=trim($_RQ['ids'],';');
	if($ids){
		$ids=explode(';',$ids);
	}else{
		$ids=array();
	}
	if($_RQ['id']){
		$ids[]=$_RQ['id'];
	}
	if($ids){
		foreach($ids as $name){
				$check=pdo_getcolumn('core_plugin_tables',array('name'=>$name,'plugin_name'=>$_SESSION['module']['plugin_name']),'id');
				$plugin_name=$_SESSION['module']['plugin_name'];
				if(!$check){
					$data=array(
						'plugin_name'=>$plugin_name,
						'name'=>$name,
					);
					pdo_insert('core_plugin_tables',$data);
				}
		}
		exi('添加成功！');
	}
	exi('请先选择要添加的数据表！','error');
}
if ($_RQ['op'] == 'table_del') {
	//删除忽略设置
	$id=intval($_RQ['id']);
	if($id){
		pdo_delete('core_plugin_tables',array('id'=>$id));
	}
	$del=trim($_RQ['del'],';');
	if($del){
		$del=explode(';',$del);
		foreach($del as $id){
			$id=intval($id);
			if($id){
				pdo_delete('core_plugin_tables',array('id'=>$id));
			}
		}
	}
	exi('删除成功！');
}
if($_RQ['op']=='star'){
	$id=intval($_RQ['id']);
	if(!$id){
		exi('参数错误！','error');
	}
	$update=array();
	$post=get_postdata();
	if(isset($post['star'])){
		$update['star']=$post['star'];
	}
	if($update){
		pdo_update('core_plugins',$update,array('id'=>$id));
	}
	exi('操作成功！');
}
function get_dirname($file){
	$dir=dirname($file);
	if(!is_dir($dir)){
		$dir=get_dirname($dir);
	}
	return $dir;
}